package com.goldcn.user.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goldcn.common.consts.RestConst;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.model.DataResult;
import com.goldcn.common.util.CommonUtils;
import com.goldcn.common.util.IdGen;
import com.goldcn.config.ProConstants;
import com.goldcn.enums.ErpInterfaceCfgEnum;
import com.goldcn.enums.RoleCodeEnum;
import com.goldcn.enums.SmsTempEnum;
import com.goldcn.enums.TopDeptEnum;
import com.goldcn.interceptor.SystemContext;
import com.goldcn.user.dao.*;
import com.goldcn.user.dto.OrganizationalMoreDto;
import com.goldcn.user.dto.OrganizationalSelectDto;
import com.goldcn.user.dto.StateDto;
import com.goldcn.user.dto.UserCountDto;
import com.goldcn.user.model.*;
import com.goldcn.user.vo.OrganizationalMoreVo;
import com.goldcn.util.CommonTools;
import com.goldcn.util.HttpUtil;
import com.goldcn.util.PinyinUtil;
import com.google.common.base.Objects;
import com.google.common.base.Strings;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.text.Collator;
import java.util.*;

/**
 * Created by 1111 on 2016/11/8.
 */
@Service
@Transactional
public class OrganizationalService {
    @Autowired
    OrganizationalMapper organizationalMapper;

    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Autowired
    UserLoginMapper userLoginMapper;

    @Autowired
    UserTransferMapper userTransferMapper;

    @Autowired
    UserInfoService userInfoService;
    @Autowired
    UserTransferService userTransferService;

    @Autowired
    CountService countService;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    CompanyInfoMapper companyInfoMapper;

    @Autowired
    ErpInterfaceService erpInterfaceService;

    private Logger logger = Logger.getLogger(OrganizationalService.class);


    @Autowired
    ErrErpBaseMapper errErpBaseMapper;

    @Autowired
    ConfigService configService;

    @Autowired
    RoleService roleService;


    @Autowired
    HomepageMapper homepageMapper;

    @Autowired
    SubjectMapper subjectMapper;

    @Autowired
    HotWordMapper hotWordMapper;


    @Autowired
    CompanyDecorationService companyDecorationService;

    public Role getRole(Long companyID, Integer code) {
        List<Role> list = roleService.selAdmin(companyID, code);
        if (CollectionUtils.isEmpty(list)) {
            throw new ServiceException("未获取到管理员角色", RestConst.ErrorCode.SERVICE_FAIL);
        }
        return list.get(0);
    }

    public Long addOrganizational(OrganizationalMoreDto organizational) {
        Organizational oz = organizationalMapper.selectByName(organizational.getOrganizationalName(), SystemContext.getCompanyID());
        if (oz != null) {
            throw new ServiceException("该组织架构已经存在:" + organizational.getOrganizationalName(), RestConst.ErrorCode.FORM_FAIL);
        }
        //新增组织关闭手机号码的验证 对于已经存在的号码可以作为在app/H5端注册会员 因此屏蔽此操作
//        UserInfo ui1 = userInfoMapper.selectByPhone(organizational.getContactPhone());
//        Organizational orgz = organizationalMapper.selectByContactPhone(organizational.getContactPhone());
//        if(ui1 != null || orgz != null){
//            throw new ServiceException(organizational.getContactPhone()+"该手机号已经存在",RestConst.ErrorCode.FORM_FAIL);
//        }

        organizational.setoID(IdGen.get().nextId());

        Count count = new Count();//会员顾问统计表
        UserCountDto userCountDto = new UserCountDto(); //订单统计表

        switch (organizational.getLevel()) {
            case 2:
                count.setBranchID(organizational.getoID());
                userCountDto.setBranchID(organizational.getoID());
                break;
            case 3:
                if (organizational.getBranchID() == null) {
                    throw new ServiceException("请选择上级分行", RestConst.ErrorCode.FORM_FAIL);
                }
                organizational.setTwoLevelBranchID(null);
                count.setBranchID(organizational.getBranchID());
                count.setTwoLevelBranchID(organizational.getoID());

                userCountDto.setBranchID(organizational.getBranchID());
                userCountDto.setTwoLevelBranchID(organizational.getoID());
                break;
            case 4:
                if (organizational.getBranchID() == null || organizational.getTwoLevelBranchID() == null) {
                    throw new ServiceException("请选择上级二级分行和分行", RestConst.ErrorCode.FORM_FAIL);
                }
                count.setBranchID(organizational.getBranchID());
                count.setTwoLevelBranchID(organizational.getTwoLevelBranchID());
                count.setSubbranchID(organizational.getoID());

                userCountDto.setBranchID(organizational.getBranchID());
                userCountDto.setTwoLevelBranchID(organizational.getTwoLevelBranchID());
                userCountDto.setSubbranchID(organizational.getoID());
                break;
            default:
                throw new ServiceException("参数传入错误", RestConst.ErrorCode.FORM_FAIL);
        }

        countService.addCount(count); //插入会员顾问统计表
        DataResult result = HttpUtil.httpPost(ProConstants.operateOrderCount, userCountDto, restTemplate);
        if (result.getIsSuccess() != 1) {
            throw new ServiceException("生成订单统计表失败,调用bank服务出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        organizational.setCompanyID(SystemContext.getCompanyID());


        //每添加一个组织架构，就新增相应的管理员，组织架构编号生成管理员的账号
        UserInfo ui = new UserInfo();
        ui.setUserID(IdGen.get().nextId());
        organizational.setAdminID(ui.getUserID());
        organizationalMapper.insert(organizational);
        ui.setType(1);
        ui.setIsAdmin(1);
        ui.setOrganizationalID(organizational.getoID());
        ui.setAccount(organizational.getCode());  //组织架构编号生成管理员的账号
        ui.setPassWord(CommonUtils.MD5(organizational.getPassWord()));
        ui.setName("admin");
        ui.setNickName("管理员");
        if (org.apache.commons.lang.StringUtils.isNotEmpty(organizational.getContactPhone())) {
            ui.setMobile(organizational.getContactPhone());
        }
        try {
            userInfoService.addUserInfo(ui);
        } catch (Exception e) {
            System.out.print(e);
            throw new ServiceException("管理员账号已存在", RestConst.ErrorCode.DATABASE_ERROR);
        }
        //给新增的管理员赋予相应的角色
        UserRole userRole = new UserRole();

        switch (organizational.getLevel()) {
            case 1:
                userRole.setRoleID(getRole(SystemContext.getCompanyID(), RoleCodeEnum.TOP.getCode()).getRoleID());
                break;
            case 2:
                userRole.setRoleID(getRole(SystemContext.getCompanyID(), RoleCodeEnum.SECOND.getCode()).getRoleID());
                break;
            case 3:
                userRole.setRoleID(getRole(SystemContext.getCompanyID(), RoleCodeEnum.THIRD.getCode()).getRoleID());
                break;
            case 4:
                userRole.setRoleID(getRole(SystemContext.getCompanyID(), RoleCodeEnum.FOURTH.getCode()).getRoleID());
                break;
        }
        userRole.setID(IdGen.get().nextId());
        userRole.setUserID(ui.getUserID());
        userRoleMapper.insert(userRole);

        //抛转架构两次 1001 1002
        if (!configService.isOpenErp()) {
            return organizational.getoID();
        }
        try {
            int i = (int) erpInterfaceService.addOrUpdateOrgForErp(organizational, 0, CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.ACCOUNTCODE.getCode()));
            //int j = (int) erpInterfaceService.addOrUpdateOrgForErp(organizational, 0, CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.ACCOUNTELSECODE.getCode()));
            if (i == 1) {
                logger.info("调用增加架构成功");
            } else {
                logger.info("调用修增加构失败,架构信息:" + organizational.getoID() + ":--" + organizational.getOrganizationalName());
            }
        } catch (Exception e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("mobile", CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.TELEPHONE.getCode())); //下单人手机
            jsonObject.put("type", SmsTempEnum.ERP_EXCEPTION.getCode());
            jsonObject.put("param", new String[]{"对接ERP组织信息失败:组织ID为" + organizational.getoID()});
            DataResult resultSms = HttpUtil.httpPost(ProConstants.SMS + "/notice", jsonObject, restTemplate);
            if (resultSms.getIsSuccess() != 1) {
                logger.info("发送短信失败");
            }

            ErrErpBase errErpBase = new ErrErpBase();
            errErpBase.setErrorId(IdGen.get().nextId());
            errErpBase.setInfoId(organizational.getoID());
            errErpBase.setAddTime(System.currentTimeMillis());
            errErpBase.setType("1");
            errErpBaseMapper.insertSelective(errErpBase);
            logger.info("修改架构调用erp失败,失败架构是:" + organizational.getOrganizationalName() + "---" + organizational.getoID());
        }
        return organizational.getoID();
    }

    public Long addOrganizationalForNewVersion(OrganizationalMoreDto organizational) {

        Organizational oz = organizationalMapper.selectByName(organizational.getOrganizationalName(), SystemContext.getCompanyID());
        if (oz != null) {
            throw new ServiceException("该组织架构已经存在:" + organizational.getOrganizationalName(), RestConst.ErrorCode.FORM_FAIL);
        }
        //新增组织关闭手机号码的验证 对于已经存在的号码可以作为在app/H5端注册会员 因此屏蔽此操作
//        UserInfo ui1 = userInfoMapper.selectByPhone(organizational.getContactPhone());
//        Organizational orgz = organizationalMapper.selectByContactPhone(organizational.getContactPhone());
//        if(ui1 != null || orgz != null){
//            throw new ServiceException(organizational.getContactPhone()+"该手机号已经存在",RestConst.ErrorCode.FORM_FAIL);
//        }

        organizational.setoID(IdGen.get().nextId());

        Count count = new Count();//会员顾问统计表
        UserCountDto userCountDto = new UserCountDto(); //订单统计表

        switch (organizational.getLevel()) {
            case 2:
                count.setBranchID(organizational.getoID());
                userCountDto.setBranchID(organizational.getoID());
                break;
            case 3:
                if (organizational.getBranchID() == null) {
                    throw new ServiceException("请选择上级分行", RestConst.ErrorCode.FORM_FAIL);
                }
                organizational.setTwoLevelBranchID(null);
                count.setBranchID(organizational.getBranchID());
                count.setTwoLevelBranchID(organizational.getoID());

                userCountDto.setBranchID(organizational.getBranchID());
                userCountDto.setTwoLevelBranchID(organizational.getoID());
                break;
            case 4:
                if (organizational.getBranchID() == null || organizational.getTwoLevelBranchID() == null) {
                    throw new ServiceException("请选择上级二级分行和分行", RestConst.ErrorCode.FORM_FAIL);
                }
                count.setBranchID(organizational.getBranchID());
                count.setTwoLevelBranchID(organizational.getTwoLevelBranchID());
                count.setSubbranchID(organizational.getoID());

                userCountDto.setBranchID(organizational.getBranchID());
                userCountDto.setTwoLevelBranchID(organizational.getTwoLevelBranchID());
                userCountDto.setSubbranchID(organizational.getoID());
                break;
            default:
                throw new ServiceException("参数传入错误", RestConst.ErrorCode.FORM_FAIL);
        }

        countService.addCount(count); //插入会员顾问统计表
        DataResult result = HttpUtil.httpPost(ProConstants.operateOrderCount, userCountDto, restTemplate);
        if (result.getIsSuccess() != 1) {
            throw new ServiceException("生成订单统计表失败,调用bank服务出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        organizational.setCompanyID(SystemContext.getCompanyID());


        Long adminID = organizational.getAdminID();

        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(adminID);
        if (userInfo == null) {

        } else {
            organizational.setCode(userInfo.getAccount());
            organizational.setContacts(userInfo.getName());
            organizational.setContactPhone(userInfo.getMobile());
            organizational.setEmail(userInfo.getEmail());
        }
        List<Organizational> organizationals = organizationalMapper.selectByAdminID(adminID);
        if (CollectionUtils.isNotEmpty(organizationals)) {
            throw new ServiceException("该员工已经是其他部门的管理者了", RestConst.ErrorCode.SERVICE_FAIL);
        }
        organizationalMapper.insert(organizational);


        initShopMall(organizational);


        if (adminID != null && adminID != 0) {
            UserInfo userInfo1 = userInfoMapper.selectByPrimaryKey(adminID);
            if (userInfo1 != null) {
                UserInfo ui = new UserInfo();
                ui.setUserID(adminID);
                ui.setIsAdmin(1);//部门管理员
                //更新管理者的部门
                ui.setOrganizationalID(organizational.getoID());
                ui.setLastOrganizationalID(userInfo1.getOrganizationalID());
                ui.setLastTransferTime(System.currentTimeMillis());
                userInfoMapper.updateByPrimaryKeySelective(ui);

                userTransferService.saveUserTransferRecord(ui, organizational, 1);
                //todo 更新下线的部门
                userInfoService.updateEmployOffline(ui);
                //给新增的管理员赋予相应的角色
                UserRole userRole = new UserRole();
                switch (organizational.getLevel()) {
                    case 1:
                        userRole.setRoleID(getRole(SystemContext.getCompanyID(), RoleCodeEnum.TOP.getCode()).getRoleID());
                        break;
                    case 2:
                        userRole.setRoleID(getRole(SystemContext.getCompanyID(), RoleCodeEnum.SECOND.getCode()).getRoleID());
                        break;
                    case 3:
                        userRole.setRoleID(getRole(SystemContext.getCompanyID(), RoleCodeEnum.THIRD.getCode()).getRoleID());
                        break;
                    case 4:
                        userRole.setRoleID(getRole(SystemContext.getCompanyID(), RoleCodeEnum.FOURTH.getCode()).getRoleID());
                        break;
                }
                userRole.setID(IdGen.get().nextId());
                userRole.setUserID(ui.getUserID());
                userRoleMapper.insert(userRole);
            }

        }


        //抛转架构两次 1001 1002
        if (!configService.isOpenErp()) {
            return organizational.getoID();
        }
        try {
            int i = (int) erpInterfaceService.addOrUpdateOrgForErp(organizational, 0, CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.ACCOUNTCODE.getCode()));
            // int j = (int) erpInterfaceService.addOrUpdateOrgForErp(organizational, 0, CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.ACCOUNTELSECODE.getCode()));
            if (i == 1) {
                logger.info("调用增加架构成功");
            } else {
                logger.info("调用修增加构失败,架构信息:" + organizational.getoID() + ":--" + organizational.getOrganizationalName());
            }
        } catch (Exception e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("mobile", CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.TELEPHONE.getCode())); //下单人手机
            jsonObject.put("type", SmsTempEnum.ERP_EXCEPTION.getCode());
            jsonObject.put("param", new String[]{"对接ERP组织信息失败:组织ID为" + organizational.getoID()});
            DataResult resultSms = HttpUtil.httpPost(ProConstants.SMS + "/notice", jsonObject, restTemplate);
            if (resultSms.getIsSuccess() != 1) {
                logger.info("发送短信失败");
            }

            ErrErpBase errErpBase = new ErrErpBase();
            errErpBase.setErrorId(IdGen.get().nextId());
            errErpBase.setInfoId(organizational.getoID());
            errErpBase.setAddTime(System.currentTimeMillis());
            errErpBase.setType("1");
            errErpBaseMapper.insertSelective(errErpBase);
            logger.info("修改架构调用erp失败,失败架构是:" + organizational.getOrganizationalName() + "---" + organizational.getoID());
        }
        return organizational.getoID();
    }


    /**
     * 修改组织架构
     *
     * @param organizational
     * @return
     */
    public String updateOrganizational(Organizational organizational) {
        if (organizational.getOrganizationalName().equals(organizational.getOrganizationalNameOld())) {
            Long count = organizationalMapper.countByname(organizational.getOrganizationalName(), SystemContext.getCompanyID());
            if (count > 1)
                throw new ServiceException("该组织架构已经存在:" + organizational.getOrganizationalName(), RestConst.ErrorCode.FORM_FAIL);
        } else {
            Long count = organizationalMapper.countByname(organizational.getOrganizationalName(), SystemContext.getCompanyID());
            if (count > 0)
                throw new ServiceException("该组织架构已经存在:" + organizational.getOrganizationalName(), RestConst.ErrorCode.FORM_FAIL);
        }

//        UserInfo ui1 = userInfoMapper.selectByPhone(organizational.getContactPhone());
//        Organizational orgz = organizationalMapper.selectByContactPhone(organizational.getContactPhone());
//        if(ui1 != null || orgz != null){
//            throw new ServiceException(organizational.getContactPhone()+"该手机号已经存在",RestConst.ErrorCode.FORM_FAIL);
//        }
        organizational.setCode(null);
        organizational.setTwoLevelBranchID(null);
        organizational.setBranchID(null);
        organizational.setLevel(null);
        organizationalMapper.updateByPrimaryKeySelective(organizational);
        if (!configService.isOpenErp()) {
            return "success";
        }
        try {
            erpInterfaceService.addOrUpdateOrgForErp(organizational, 1, CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.ACCOUNTCODE.getCode()));
            //erpInterfaceService.addOrUpdateOrgForErp(organizational, 1, CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.ACCOUNTELSECODE.getCode()));
        } catch (Exception e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("mobile", CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.TELEPHONE.getCode())); //下单人手机
            jsonObject.put("type", SmsTempEnum.ERP_EXCEPTION.getCode());
            jsonObject.put("param", new String[]{"对接ERP组织信息失败:组织ID为" + organizational.getoID()});
            DataResult resultSms = HttpUtil.httpPost(ProConstants.SMS + "/notice", jsonObject, restTemplate);
            if (resultSms.getIsSuccess() != 1) {
                logger.info("发送短信失败");
            }

            logger.info("修改组织信息对接ERP失败" + organizational.getoID());
        }
        return "success";
    }

    public String updateOrganizationalForGz(OrganizationalMoreDto organizational) {
        Organizational oldOrganizational = organizationalMapper.selectByPrimaryKey(organizational.getoID());
        if (oldOrganizational == null) {
            throw new ServiceException("该部门已被删除", RestConst.ErrorCode.FORM_FAIL);
        }
        Organizational newOrganizational = new Organizational();

        if (organizational.getAdminID() == null || organizational.getAdminID() == 0) {
            UserInfo userInfo = userInfoMapper.selectByPrimaryKey(oldOrganizational.getAdminID());
            if (userInfo != null) {
                userInfo.setIsAdmin(2);
                userInfoMapper.updateByPrimaryKeySelective(userInfo);
                userTransferService.parseEmployee(userInfo.getUserID());
            }
            newOrganizational.setoID(oldOrganizational.getoID());
            newOrganizational.setOrganizationalName(organizational.getOrganizationalName());
            organizationalMapper.updateByPrimaryKeySelective(newOrganizational);
            organizationalMapper.clearAdmin(newOrganizational.getoID());
            return "success";
        }

        if (!Objects.equal(oldOrganizational.getAdminID(), organizational.getAdminID())) {
            List<Organizational> organizationals_ = organizationalMapper.selectByAdminID(organizational.getAdminID());
            if (CollectionUtils.isNotEmpty(organizationals_)) {
                throw new ServiceException("该员工已经是管理员", RestConst.ErrorCode.FORM_FAIL);
            }
            //之前的管理员降为普通员工
            if (oldOrganizational.getAdminID() != null && oldOrganizational.getAdminID() != 0) {
                organizationalMapper.clearAdmin(oldOrganizational.getAdminID());
                UserInfo userInfo = userInfoMapper.selectByPrimaryKey(oldOrganizational.getAdminID());
                userInfo.setIsAdmin(2);
                userInfoMapper.updateByPrimaryKeySelective(userInfo);
                userTransferService.parseEmployee(userInfo.getUserID());
            }

            //记录新的管理员
            newOrganizational.setAdminID(organizational.getAdminID());
            UserInfo userInfo = userInfoMapper.selectByPrimaryKey(newOrganizational.getAdminID());
            newOrganizational.setCode(userInfo.getAccount());
            newOrganizational.setContacts(userInfo.getName());
            newOrganizational.setContactPhone(userInfo.getMobile());
            newOrganizational.setEmail(userInfo.getEmail());
            userInfo.setIsAdmin(1);
            userInfo.setLastOrganizationalID(userInfo.getOrganizationalID());
            userInfo.setOrganizationalID(oldOrganizational.getoID());//更新管理员的组织架构
            userInfo.setLastTransferTime(System.currentTimeMillis());
            userInfoMapper.updateByPrimaryKeySelective(userInfo);
            userTransferService.saveUserTransferRecord(userInfo, oldOrganizational, 1);
            //todo 更新下线的部门
            userInfoService.updateEmployOffline(userInfo);
            //给新增的管理员赋予相应的角色
            UserRole userRole = new UserRole();
            switch (oldOrganizational.getLevel()) {
                case 1:
                    userRole.setRoleID(getRole(SystemContext.getCompanyID(), RoleCodeEnum.TOP.getCode()).getRoleID());
                    break;
                case 2:
                    userRole.setRoleID(getRole(SystemContext.getCompanyID(), RoleCodeEnum.SECOND.getCode()).getRoleID());
                    break;
                case 3:
                    userRole.setRoleID(getRole(SystemContext.getCompanyID(), RoleCodeEnum.THIRD.getCode()).getRoleID());
                    break;
                case 4:
                    userRole.setRoleID(getRole(SystemContext.getCompanyID(), RoleCodeEnum.FOURTH.getCode()).getRoleID());
                    break;
            }
            userRole.setID(IdGen.get().nextId());
            userRole.setUserID(userInfo.getUserID());
            userRoleMapper.insert(userRole);
        }

        newOrganizational.setoID(oldOrganizational.getoID());
        newOrganizational.setOrganizationalName(organizational.getOrganizationalName());
        // added by timpeng 2018-8-26
        if (organizational.getState() != null) {
            logger.info("修改商城状态,state=" + organizational.getState());
            //更新停用状态
            newOrganizational.setState(organizational.getState());

            //更新商城状态
            StateDto stateDto = new StateDto();
            stateDto.setuID(organizational.getoID());
            stateDto.setState(organizational.getState());
            companyInfoMapper.updateCompanyState(stateDto);
        }
        organizationalMapper.updateByPrimaryKeySelective(newOrganizational);
        return "success";
    }

    //获取上级部门
    public Long getPreDeptID(Organizational organizational) {
        if (Objects.equal(organizational.getLevel(), 2)) {
            TopDeptEnum topDeptEnum = TopDeptEnum.valuekOf(organizational.getCompanyID());
            return topDeptEnum != null ? topDeptEnum.getDeptID() : null;
        } else if (Objects.equal(organizational.getLevel(), 3)) {
            return organizational.getBranchID();
        } else if (Objects.equal(organizational.getLevel(), 4)) {
            return organizational.getTwoLevelBranchID();
        }
        return 0L;
    }

    public void moveDeptOrderToNewDept(Organizational organizational) {
        DataResult result = HttpUtil.httpGet(ProConstants.moveDeptOrderToNewDept + organizational.getoID() + "/" + organizational.getLevel(), restTemplate);
        if (result.getIsSuccess() != 1) {
            throw new ServiceException("更新订单部门信息失败", RestConst.ErrorCode.SERVICE_FAIL);
        }
    }

    public String deleteOrganizational(Long oID) {
        logger.info("删除架构");
        /*if (existOrderRecord(oID)) {
            throw new ServiceException("该组织架构已产生业务单据，不可删除", RestConst.ErrorCode.FORM_FAIL);
        }*/
        List<Organizational> ozList = organizationalMapper.selectForDeleteJudge(oID);
        if (ozList.size() > 0) {
            throw new ServiceException("该组织架构已有下级组织，不可删除", RestConst.ErrorCode.FORM_FAIL);
        }

        Organizational organizational = organizationalMapper.selectByPrimaryKey(oID);
        if (Objects.equal(organizational.getLevel(), 1)) {
            throw new ServiceException("总部不可删除", RestConst.ErrorCode.FORM_FAIL);
        }
        //List<UserInfo> uiList = userInfoMapper.selectByOID(oID);
        List<UserInfo> uiList = userInfoMapper.selectEmployeeByOID(oID);//只查询员工
        //分部内如果有员工（除了管理员外的员工），不允许删除分部，
        //之前为分部管理员，分部被删除后，此管理员变更为上一级部门的员工（例如本来是支部的管理员，删除支部后，变更为二级分部的员工）
        Integer rows = uiList.size();
        if (rows > 0) {
            if (rows == 1 && Objects.equal(uiList.get(0).getUserID(), organizational.getAdminID())) {//只剩分部管理员
                UserInfo userInfo = userInfoMapper.selectByPrimaryKey(uiList.get(0).getUserID());
                Long preDeptID = getPreDeptID(organizational);
                if (preDeptID == null) {
                    throw new ServiceException("未获取到上级组织架构", RestConst.ErrorCode.FORM_FAIL);
                }
                userInfo.setOrganizationalID(preDeptID);
                List list = organizationalMapper.selectByAdminID(userInfo.getUserID());
                /*if (list.size() == 1) {*/
                userInfo.setIsAdmin(2);
                userInfoMapper.updateByPrimaryKeySelective(userInfo);
                userTransferService.parseEmployee(userInfo.getUserID());
                /*}*/
                userInfoService.updateEmployOffline(userInfo);
            } else {
                throw new ServiceException("该组织架构已经有员工，不可删除", RestConst.ErrorCode.FORM_FAIL);
            }
        } else {
            // UserInfo userInfo = userInfoMapper.selectByPrimaryKey(uiList.get(0).getUserID());
            UserInfo userInfo = userInfoMapper.selectByPrimaryKey(organizational.getAdminID());
            if (userInfo != null) {
                List list = organizationalMapper.selectByAdminID(userInfo.getUserID());
                if (list.size() == 1) {
                    userInfo.setIsAdmin(2);
                }
                userInfoMapper.updateByPrimaryKeySelective(userInfo);
            }
        }

        Map<String, Object> params = new HashMap<>();
        switch (organizational.getLevel()) {
            case 2:
                params.put("branchID", oID);
                break;
            case 3:
                params.put("twoLevelBranchID", oID);
                break;
            case 4:
                params.put("subbranchID", oID);
                break;
            default:
                throw new ServiceException("不可删除", RestConst.ErrorCode.FORM_FAIL);
        }

        countService.delteCountByOID(params);  //删除用户统计表记录
        //删除订单统计表记录
        logger.info("删除统计记录表");
        DataResult result = HttpUtil.httpPost(ProConstants.operateOrderCount + "/delete", params, restTemplate);
        if (result.getIsSuccess() != 1) {
            throw new ServiceException("删除订单统计表记录失败,调用bank服务出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        logger.info("删除统计记录表成功");
        Organizational deleteOrg = organizationalMapper.selectByPrimaryKey(oID);
        if (deleteOrg != null) {
            logger.info("删除的架构信息为:id" + deleteOrg.getoID() + "架构名字:" + deleteOrg.getOrganizationalName());
        }

        deleteOrg.setState(1);
        organizationalMapper.updateByPrimaryKeySelective(deleteOrg);
        //moveDeptOrderToNewDept(deleteOrg);

        try {
            erpInterfaceService.deleteOrgErp(organizational.getoID() + "");
        } catch (Exception e) {
            logger.info("组织删除对接ERP失败" + organizational.getoID());
        }
        logger.info("删除架构成功");

        return "success";
    }

    public Object selectOrganizationalMore(Long oID) throws Exception {
        Organizational organizational = organizationalMapper.selectByPrimaryKey(oID);
        OrganizationalMoreVo moreVo = new OrganizationalMoreVo();
        BeanUtils.copyProperties(moreVo, organizational);
        moreVo.setPathName(retPathName(moreVo));
        switch (moreVo.getLevel()) {
            case 2:
                moreVo.setPathName("总部");
                break;
            case 3:
                Organizational oz = organizationalMapper.selectByPrimaryKey(moreVo.getBranchID());
                moreVo.setPathName("总部/" + oz.getOrganizationalName());
                break;
            case 4:
                Organizational oz1 = organizationalMapper.selectByPrimaryKey(moreVo.getBranchID());
                Organizational oz2 = organizationalMapper.selectByPrimaryKey(moreVo.getTwoLevelBranchID());
                moreVo.setPathName("总部/" + oz1.getOrganizationalName() + "/" + oz2.getOrganizationalName());
                break;
        }
        return moreVo;
    }

    public Organizational selectByOID(Long oID) {
        return organizationalMapper.selectByPrimaryKey(oID);
    }

    //查询总行信息
    public Organizational selectHeadCCB(Long companyID) {
        return organizationalMapper.selectHeadCCB(companyID);
    }

    //查询下属银行列表信息[仅获取下一级]
    public PageInfo selectSubBankList(Long oID, int pageNum, int pageSize) {
        if (Objects.equal(oID, SystemContext.getCompanyID())) {
            TopDeptEnum topDeptEnum = TopDeptEnum.valuekOf(SystemContext.getCompanyID());
            if (topDeptEnum == null) {
                throw new ServiceException("未找到总部信息", RestConst.ErrorCode.DATABASE_ERROR);
            }
            oID = topDeptEnum.getDeptID();
        }
        Organizational organizational = organizationalMapper.selectByPrimaryKey(oID);
        if (organizational == null) {
            throw new ServiceException("ID错误，未查到组织信息", RestConst.ErrorCode.DATABASE_ERROR);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Organizational> organizationalList = new ArrayList<>();
        Organizational oz = new Organizational();

        switch (organizational.getLevel()) {
            case 1:
                oz.setLevel(2);
                oz.setCompanyID(SystemContext.getCompanyID());
                organizationalList = organizationalMapper.selectSubBankList(oz);
                break;
            case 2:
                oz.setLevel(3);
                oz.setBranchID(organizational.getoID());
                organizationalList = organizationalMapper.selectSubBankList(oz);
                break;
            case 3:
                oz.setLevel(4);
                oz.setTwoLevelBranchID(organizational.getoID());
                organizationalList = organizationalMapper.selectSubBankList(oz);
                break;
        }
        PageInfo<Organizational> page = new PageInfo(organizationalList);
        return page;
    }

    //查询下属银行列表信息[仅获取下一级]包含本部
    public PageInfo selectSubBankListV2(Long oID, int pageNum, int pageSize) {
        if (Objects.equal(oID, SystemContext.getCompanyID())) {
            TopDeptEnum topDeptEnum = TopDeptEnum.valuekOf(SystemContext.getCompanyID());
            if (topDeptEnum == null) {
                throw new ServiceException("未找到总部信息", RestConst.ErrorCode.DATABASE_ERROR);
            }
            oID = topDeptEnum.getDeptID();
        }
        Organizational organizational = organizationalMapper.selectByPrimaryKey(oID);
        if (organizational == null) {
            throw new ServiceException("ID错误，未查到组织信息", RestConst.ErrorCode.DATABASE_ERROR);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Organizational> organizationalList = new ArrayList<>();
        Organizational oz = new Organizational();
        switch (organizational.getLevel()) {
            case 1:
                oz.setLevel(2);
                oz.setCompanyID(SystemContext.getCompanyID());
                organizationalList = organizationalMapper.selectSubBankList(oz);
                break;
            case 2:
                oz.setLevel(3);
                oz.setBranchID(organizational.getoID());
                organizationalList = organizationalMapper.selectSubBankList(oz);
                organizational.setOrganizationalName(organizational.getOrganizationalName() + "本部");
                organizationalList.add(0, organizational);
                break;
            case 3:
                oz.setLevel(4);
                oz.setTwoLevelBranchID(organizational.getoID());
                organizationalList = organizationalMapper.selectSubBankList(oz);
                break;
        }
        PageInfo<Organizational> page = new PageInfo(organizationalList);
        return page;
    }


    //搜索下级所有银行列表
    public PageInfo selectBankSearchList(OrganizationalSelectDto selectDto, int pageNum, int pageSize) {
        Organizational organizational = organizationalMapper.selectByPrimaryKey(selectDto.getoID());
        if (organizational == null) {
            throw new ServiceException("ID错误，未查到组织信息", RestConst.ErrorCode.DATABASE_ERROR);
        }
        //PageHelper.startPage(pageNum, pageSize);
        List<Organizational> organizationalList = new ArrayList<>();
        Organizational oz = new Organizational();
        switch (organizational.getLevel()) {
            case 1:
                oz.setCompanyID(SystemContext.getCompanyID());
                oz.setOrganizationalName(selectDto.getOrganizationalName());
                organizationalList = organizationalMapper.selectSubBankList(oz);
                break;
            case 2:
                oz.setBranchID(organizational.getoID());
                oz.setOrganizationalName(selectDto.getOrganizationalName());
                organizationalList = organizationalMapper.selectSubBankList(oz);
                break;
            case 3:
                oz.setTwoLevelBranchID(organizational.getoID());
                oz.setOrganizationalName(selectDto.getOrganizationalName());
                organizationalList = organizationalMapper.selectSubBankList(oz);
        }


        for (Organizational _organizational : organizationalList) {//上级部门
            _organizational.setOpathName(retPathName(_organizational));
            _organizational.setAllName(new StringBuffer().append(_organizational.getOpathName()).append("/")
                    .append(_organizational.getOrganizationalName()).toString());

            if (!Strings.isNullOrEmpty(_organizational.getAllName())) {
                String[] deptName = _organizational.getAllName().split("/");
                Integer level = deptName.length;
                String first = level > 0 ? PinyinUtil.cn2Spell(deptName[0], true) : "";
                String second = level > 1 ? PinyinUtil.cn2Spell(deptName[1], true) : "";
                String third = level > 2 ? PinyinUtil.cn2Spell(deptName[2], true) : "";
                String fourth = level > 3 ? PinyinUtil.cn2Spell(deptName[3], true) : "";

                int al = first.length();
                int bl = second.length();
                int cl = third.length();
                int dl = fourth.length();
                int[] array = {al, bl, cl, dl};
                int max = NumberUtils.max(array);
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < max; i++) {
                    //sb.append(al>i ? first.substring(i,i+1) : "0" );
                    sb.append(bl > i ? second.substring(i, i + 1) : "0");
                    sb.append(cl > i ? third.substring(i, i + 1) : "0");
                    sb.append(dl > i ? fourth.substring(i, i + 1) : "0");
                }
                _organizational.setPinyinDept(sb.toString());

            }
        }

        //
        //organizationalList = getPageList(organizationalList,pageNum,pageSize);
        final Comparator<Object> com = Collator.getInstance(Locale.US);
        //final Collator com = Collator.getInstance(ULocale.SIMPLIFIED_CHINESE);
        Collections.sort(organizationalList, new Comparator<Organizational>() {
            @Override
            public int compare(Organizational o1, Organizational o2) {
                return com.compare(o1.getPinyinDept(), o2.getPinyinDept());
            }
        });
        organizationalList = getPageList(organizationalList, pageNum, pageSize);

        return new PageInfo(organizationalList);

    }

    private Page getPageList(List<Organizational> organizationalList, int pageNum, int pageSize) {
        int size = organizationalList.size();
        int start = (pageNum - 1) * pageSize;//包括[
        int end = start + pageSize;//不包括)

        if (end > size) {
            end = size;
        }
        //List<Organizational> organizationals = Lists.newArrayList();
        Page page = new Page(pageNum, pageSize);
        if (start < size) {
            for (int i = start; i < end; i++) {
                page.add(organizationalList.get(i));
            }
        }
        page.setStartRow(start + 1);
        page.setEndRow(end);
        page.setTotal(size);
        page.setPages((size % pageSize == 0) ? size / pageSize : size / pageSize + 1);


        return page;
    }

    private String retPathName(Organizational orgVo) {
        String pathName = null;
        switch (orgVo.getLevel()) {
            case 2:
                pathName = ("总部");
                break;
            case 3:
                Organizational oz = organizationalMapper.selectByPrimaryKey(orgVo.getBranchID());
                pathName = ("总部/" + oz.getOrganizationalName());
                break;
            case 4:
                Organizational oz1 = organizationalMapper.selectByPrimaryKey(orgVo.getBranchID());
                Organizational oz2 = organizationalMapper.selectByPrimaryKey(orgVo.getTwoLevelBranchID());
                pathName = ("总部/" + oz1.getOrganizationalName() + "/" + oz2.getOrganizationalName());
                break;
        }
        return pathName;
    }

    public Object getLevel1(Long companyID) {
        return organizationalMapper.getLevel1Org(companyID).getoID();
    }

    public String pathName(Organizational orgVo) {
        String pathName = null;
        switch (orgVo.getLevel()) {
            case 1:
                pathName = "总部";
                break;
            case 2:
                pathName = "总部";
                break;
            case 3:
                Organizational oz = organizationalMapper.selectByPrimaryKey(orgVo.getBranchID());
                pathName = "总部/" + oz.getOrganizationalName();
                break;
            case 4:
                Organizational oz1 = organizationalMapper.selectByPrimaryKey(orgVo.getBranchID());
                Organizational oz2 = organizationalMapper.selectByPrimaryKey(orgVo.getTwoLevelBranchID());
                pathName = ("总部/" + oz1.getOrganizationalName() + "/" + oz2.getOrganizationalName());
                break;
        }
        return pathName;
    }

    /**
     * 根据组织名字得到组织id的list
     *
     * @param organizationalId
     * @param searchName
     * @return
     */
    public Object getOrgIDListByName(Long organizationalId, String searchName) {
        Organizational organizational = organizationalMapper.selectByPrimaryKey(organizationalId);
        List<Organizational> organizationalList = organizationalMapper.selectOrgByLikeName(searchName, organizational.getCompanyID());
        List<Long> resultList = new ArrayList<>();
        for (Organizational org : organizationalList) {
            if (organizational.getLevel() == 1) {
                resultList.add(org.getoID());
            } else {
                if (org.getoID().compareTo(organizationalId) == 0
                        || (null != org.getBranchID() && org.getBranchID().compareTo(organizationalId) == 0)
                        || (org.getTwoLevelBranchID() != null && org.getTwoLevelBranchID().compareTo(organizationalId) == 0)) {
                    resultList.add(org.getoID());
                }
            }
        }
        return resultList;
    }

    public Map<Long, String> getOrgIdLevelLikeName(Long organizationalId, String searchName) {
        List<Long> resultList = (List<Long>) getOrgIDListByName(organizationalId, searchName);
        Map<Long, String> result = new HashMap<>();
        if (resultList != null && resultList.size() != 0) {
            for (Long oid : resultList) {
                Organizational organizational = organizationalMapper.selectByPrimaryKey(oid);
                result.put(oid, organizational.getLevel().toString());
            }
        }
        return result;
    }


    public int updateUserInfo(UserInfo userInfo) {
        CompanyInfo companyInfo = companyInfoMapper.selectByPrimaryKey(userInfo.getShopID());
        if (Objects.equal(userInfo.getIsAdmin(), 1)) {
            companyInfo.setAdminID(userInfo.getUserID());
            companyInfoMapper.updateByPrimaryKey(companyInfo);
            userInfoMapper.updateEmployeeByShopID(userInfo.getShopID());
        }
        //员工换店铺，员工下面的会员归属于上一级
        updateMemberOffline(userInfo);
        int retun = userInfoMapper.updateByPrimaryKeySelective(userInfo);
        //没有店长更新companyInfo表
        List<UserInfo> userInfos = userInfoMapper.getShopManagerByShopID(userInfo.getShopID());
        if (userInfos == null || userInfos.size() == 0) {
            companyInfo.setAdminID(null);
            companyInfoMapper.updateByPrimaryKey(companyInfo);
        }
        return retun;
    }

    private void updateMemberOffline(UserInfo userInfo) {
        //员工换店铺，下面的会员从属上一级
        UserInfo user = userInfoMapper.selectByPrimaryKey(userInfo.getUserID());
        if (user.getShopID() == null || user.getShopID() == 0L || !Objects.equal(user.getShopID(), userInfo.getShopID())) {
            List<UserInfo> list = userInfoMapper.selectByPaterID(userInfo.getUserID());
            if (!CollectionUtils.isEmpty(list)) {
                Long storeManage = Long.valueOf(userInfoService.getStoreManagerByUserID(userInfo.getUserID()) + "");
                for (UserInfo userd : list) {
                    userd.setPaterID(storeManage);
                    userInfoMapper.updateByPrimaryKeySelective(userd);
                }
            }
        }

    }

    public Object updateShopBossForCheck(UserInfo userInfo) {
        //0 表示该店铺还没指定店长   1表示已有店长
        CompanyInfo companyInfo = companyInfoMapper.selectByPrimaryKey(userInfo.getShopID());
        // List<UserInfo> userInfos = userInfoMapper.getShopManagerByShopID(shopID);
        if (companyInfo != null && companyInfo.getAdminID() != null && !Objects.equal(companyInfo.getAdminID(), 0L)) {
            return "1";
        }
        return "0";

    }

    public Map<String, Object> getAllOrgCount(Long companyID) {
        return organizationalMapper.getAllOrgCount(companyID);
    }

    public Organizational getLevel1Org(Long companyID) {
        return organizationalMapper.getLevel1Org(companyID);
    }

    public Organizational selectTopDept(Long companyID) {
        return organizationalMapper.selectTopDept(companyID);
    }


    public Object getMallInfo(Long companyID) {
        return companyInfoMapper.getMallInfo(companyID);
    }


    /**
     * 获取商城的合伙人资料
     *
     * @param shopID
     * @return
     */
    public Object getOrgInfoByMallShopID(Long shopID) {
        return organizationalMapper.getOrgInfoByMallShopID(shopID);
    }


    /**
     * 初始化商城数据
     * 合伙人新建时默认新建一个空的商城
     * <p>
     * added by pengzh 2018-4-12
     *
     * @param org
     * @return
     */
    private Object initShopMall(Organizational org) {
        CompanyInfo companyInfo = new CompanyInfo();
        Long timestamp = CommonUtils.getCurTimestamp();
        companyInfo.setCompanyInfoID(IdGen.get().nextId());
        companyInfo.setAddTime(timestamp);
        companyInfo.setUpdateTime(timestamp);
        companyInfo.setType(3);
        companyInfo.setIsAudit(1);
        companyInfo.setState(0);
        companyInfo.setUserID(org.getAdminID());
        companyInfo.setAdminID(org.getAdminID());
        companyInfo.setCompanyName(org.getOrganizationalName());
        companyInfo.setCompanyID(SystemContext.getCompanyID());
        companyInfo.setOrgID(org.getoID());

        companyInfoMapper.insertSelective(companyInfo);

        //增加对应店铺信息
        companyDecorationService.insert(companyInfo);

        //begin: 生成小商城首页模板数据 added by pengzh 2018-4-11
        Long newCompanyID = companyInfo.getCompanyInfoID();
        HotWord hotWord = hotWordMapper.findByCompanyLimit1(ProConstants.TEMP_CompanyID);
        if (null != hotWord && null != hotWord.getId()) {
            hotWord.setId(IdGen.get().nextId());
            hotWord.setCompanyID(newCompanyID);
            hotWordMapper.insert(hotWord);
        }
        //初始化一个专题
        Subject subject = subjectMapper.selectByCompanyLimit1(ProConstants.TEMP_CompanyID);
        if (null != subject && null != subject.getId()) {
            Long subjID = IdGen.get().nextId();
            subject.setId(subjID);
            subject.setCompanyID(newCompanyID);
            subject.setAddTime(System.currentTimeMillis());
            subjectMapper.insertSelective(subject);
        }

        Map<String, Object> para = new HashMap();
        para.put("companyID", ProConstants.TEMP_CompanyID);
        List<Homepage> homepageList = homepageMapper.selectAll(para);
        if (null != homepageList && homepageList.size() > 0) {
            Integer homepageId = homepageMapper.getMaxID();
            for (Homepage homepage : homepageList) {
                homepage.setId(homepageId + 1);
                homepage.setObejctList(null);
                homepage.setTitle(null);
                homepage.setSubtitle(null);
                homepage.setObejctList(null);
                homepage.setCompanyID(newCompanyID);

                homepageId = homepage.getId();
            }
            homepageMapper.insertBatch(homepageList);
        }

        //店长
        if (null != companyInfo.getAdminID() && 3 == companyInfo.getType()) {
            UserInfo userInfo = new UserInfo();
            userInfo.setUserID(companyInfo.getAdminID());
            userInfo.setShopID(companyInfo.getCompanyInfoID());
            userInfo.setIsAdmin(1);
            userInfoService.updateByPrimaryKeySelective(userInfo);
        }
        return companyInfo;

    }

}
